package com.xiaolin.oa.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xiaolin.oa.constants.FlagConstant;
import com.xiaolin.oa.constants.OptConstant;
import com.xiaolin.oa.exception.ServiceException;
import com.xiaolin.oa.mapper.CommonProcessNodeMapper;
import com.xiaolin.oa.model.dto.CurrentUser;
import com.xiaolin.oa.model.entity.CommonProcessApprover;
import com.xiaolin.oa.model.entity.CommonProcessNode;
import com.xiaolin.oa.service.CommonProcessApproverService;
import com.xiaolin.oa.service.CommonProcessNodeService;
import com.xiaolin.oa.utils.ContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 审批流程节点表 服务实现类
 * </p>
 *
 * @author xiaolin
 * @since 2024-08-22
 */
@Service
public class CommonProcessNodeServiceImpl extends ServiceImpl<CommonProcessNodeMapper, CommonProcessNode> implements CommonProcessNodeService {
    @Autowired
    private CommonProcessApproverService processApproverService;

    @Autowired
    private CommonProcessNodeMapper processNodeMapper;

    @Autowired
    private ContextUtil contextUtil;

    @Override
    public PageInfo<CommonProcessNode> getProcessNodePage(Integer page, Integer pageSize, CommonProcessNode processNode) {
        PageHelper.startPage(page, pageSize);
        List<CommonProcessNode> processNodeList = processNodeMapper.getProcessNodeList(processNode);
        return new PageInfo<>(processNodeList);
    }

    /**
     * 校验审批流程节点唯一性
     *
     * @param processNode
     * @return
     */
    @Override
    public void checkUnique(CommonProcessNode processNode) {
        long count = processNodeMapper.selectCount(new LambdaQueryWrapper<CommonProcessNode>()
                .eq(CommonProcessNode::getProcessId, processNode.getProcessId())
                .eq(CommonProcessNode::getProcessNodeCode, processNode.getProcessNodeCode())
                .ne(Objects.nonNull(processNode.getId()), CommonProcessNode::getId, processNode.getId()));
        if (count > 0) {
            ServiceException.error("审批流程节点名重复了");
        }
    }

    @Override
    public boolean addProcessNode(CommonProcessNode processNode) {
        CurrentUser user = contextUtil.getCurrentUser();
        // 校验审批流程节点唯一性
        checkUnique(processNode);
        processNode.setCreator(user.getId());
        processNode.setUpdator(user.getId());
        processNodeMapper.insert(processNode);
        return true;
    }

    @Override
    public CommonProcessNode getProcessNode(Integer id) {
        return processNodeMapper.selectById(id);
    }

    @Override
    public boolean updateProcessNode(CommonProcessNode processNode) {
        // 校验审批流程节点唯一性
        checkUnique(processNode);
        processNodeMapper.updateById(processNode);
        return true;
    }

    @Override
    public boolean deleteProcessNode(Integer id) {
        processNodeMapper.deleteById(id);
        return true;
    }

    @Override
    public boolean configProcessNodeForUsers(Integer processNodeId, String optType, List<Integer> userIds) {
        if (CollectionUtils.isEmpty(userIds)) {
            ServiceException.error("请选择要绑定或解绑的用户");
        }
        CurrentUser user = contextUtil.getCurrentUser();
        if (OptConstant.ADD.equals(optType)) {
            // 用户绑定角色
            List<CommonProcessApprover> processApprovers = userIds.stream().map(userId -> {
                CommonProcessApprover processApprover = new CommonProcessApprover();
                processApprover.setApprover(userId);
                processApprover.setProcessNodeId(processNodeId);
                processApprover.setCreator(user.getId());
                processApprover.setUpdator(user.getId());
                return processApprover;
            }).collect(Collectors.toList());
            processApproverService.saveBatch(processApprovers);
            return true;
        } else if (OptConstant.UPDATE.equals(optType)) {
            // 用户解绑角色
            processApproverService.update(new UpdateWrapper<CommonProcessApprover>().lambda()
                    .set(CommonProcessApprover::getFlag, FlagConstant.DELETED)
                    .set(CommonProcessApprover::getUpdator, user.getId())
                    .eq(CommonProcessApprover::getProcessNodeId, processNodeId).in(CommonProcessApprover::getApprover, userIds));
            return true;
        } else {
            ServiceException.error("非法操作");
            return false;
        }
    }

    @Override
    public List<Integer> getBoundUsers(Integer processNodeId) {
        List<CommonProcessApprover> processApprovers = processApproverService.list(new LambdaQueryWrapper<CommonProcessApprover>().eq(CommonProcessApprover::getProcessNodeId, processNodeId));
        return processApprovers.stream().map(CommonProcessApprover::getApprover).collect(Collectors.toList());
    }
}
